import React, {
  forwardRef,
  useCallback,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from "react";
import {
  Button,
  Form,
  Input,
  Select,
  Switch,
  Modal,
  ProTable,
  Drawer,
  Space,
  Divider,
  Tooltip,
  AppContainer,
  Utils,
} from "knowdesign";
import message from "@/components/Message";
import { IconFont } from "@knowdesign/icons";
import { CopyOutlined, PlusOutlined } from "@ant-design/icons";
import moment from "moment";
// 引入代码编辑器
import { Controlled as CodeMirror } from "react-codemirror2";
import "codemirror/lib/codemirror.css";
//代码高亮
import "codemirror/addon/edit/matchbrackets";
import "codemirror/addon/selection/active-line";
import "codemirror/addon/edit/closebrackets";
require("codemirror/mode/xml/xml");
require("codemirror/mode/javascript/javascript");
import api from "./api";
import { defaultPagination } from "@/constants/common";
import TypicalListCard from "@/components/TypicalListCard";
import { ConfigOperate, ConfigProps, sourceList } from "./config";
import "./index.less";
import SearchFilter from "./SearchFilter";
import HttpUtils from "@/utils/HttpUtils";
import AddAndEditDataSourceModal from "./AddAndEditDataSourceModal";
import MysqlIcon from "./icon/MysqlIcon";
import HiveIcon from "./icon/HiveIcon";
import OracleIcon from "./icon/OracleIcon";
import PostGresqlIcon from "./icon/PostgresqlIcon";
import PhoenixIcon from "./icon/PhoenixIcon";

const { request } = Utils;
const { confirm } = Modal;
const { TextArea } = Input;

// 配置值详情弹窗
// eslint-disable-next-line react/display-name
const ConfigValueDetail = forwardRef((_, ref) => {
  const [visible, setVisible] = useState<boolean>(false);
  const [content, setContent] = useState<string>("");

  const onClose = () => {
    setVisible(false);
    setContent("");
  };

  useImperativeHandle(ref, () => ({
    setVisible: (status: boolean, content: string) => {
      let transformedContent = "";

      try {
        // 如果内容可以格式化为 JSON，进行处理
        transformedContent = JSON.stringify(JSON.parse(content), null, 2);
      } catch (_) {
        transformedContent = content;
      }

      setContent(transformedContent);
      setVisible(status);
    },
  }));

  return (
    <Modal
      className="config-manage-value-modal"
      title="配置值"
      visible={visible}
      centered={true}
      footer={null}
      onCancel={onClose}
      maskClosable={false}
      destroyOnClose
    >
      <CodeMirror
        value={content}
        options={{
          mode: "application/json",
          lineNumbers: true,
          lineWrapper: true,
          autoCloseBrackets: true,
          smartIndent: true,
          tabSize: 2,
        }}
        onBeforeChange={() => {
          return;
        }}
      />
    </Modal>
  );
});

export default () => {
  const [global] = AppContainer.useGlobalValue();
  const [loading, setLoading] = useState<boolean>(true);
  const [configGroupList, setConfigGroupList] = useState<
    { label: string; value: string }[]
  >([]);
  const [data, setData] = useState<ConfigProps[]>([]);
  const [pagination, setPagination] = useState<any>(defaultPagination);
  const [form] = Form.useForm();
  const editDrawerRef = useRef(null);
  const configValueModalRef = useRef(null);

  const getDsList = () => {
    HttpUtils.get(api.listType).then((res) => {
      if (res?.code === 200) {
        const options = res?.data?.map((item) => ({
          label: item,
          value: item,
        }));
        setConfigGroupList(options);
      } else {
        message.error(res?.message);
      }
    });
  };

  const getDataSourceList = (query = {}) => {
    const formData = form.getFieldsValue();
    const queryParams = {
      page: pagination.current,
      size: pagination.pageSize,
      ...formData,
      ...query,
    };

    setLoading(true);
    HttpUtils.post(api.sourcePage, queryParams).then(
      (data: any) => {
        if (data?.code === 200) {
          const res = data?.data;
          const { pageNo, pageSize, pages, total } = res.pagination;
          if (pageNo > pages && pages !== 0) {
            getDataSourceList({ page: pages });
            return false;
          }

          setPagination({
            ...pagination,
            current: pageNo,
            pageSize,
            total,
          });
          setData(res.bizData);
          setLoading(false);
        } else {
          message.error(data?.message);
        }
      },
      () => setLoading(false)
    );
  };

  const getIconComponent = (dbType: string) => {
    switch (dbType.toLowerCase()) {
      case "mysql":
        return <MysqlIcon />;
      case "postgresql":
        return <PostGresqlIcon />;
      case "oracle":
        return <OracleIcon />;
      case "sqlserver":
        return <MysqlIcon />;
      case "hive":
        return <HiveIcon />;
      case "phoenix":
        return <PhoenixIcon />;
      case "clickhouse":
        return <MysqlIcon />;
      default:
        return <MysqlIcon />;
    }
  };

  const columns = useCallback(() => {
    const baseColumns = [
      {
        title: "序号",
        dataIndex: "id",
        width: "5%",
      },
      {
        title: "数据源信息",
        dataIndex: "dsName",
        width: "10%",
        // lineClampOne: true,
        render(status: number, record) {
          return (
            <div>
              <div style={{ fontWeight: 600 }}>{record.dsName}</div>
              <div style={{ display: "flex" }}>
                {getIconComponent(record.dsType)}{" "}
                <span style={{ marginLeft: 2, color: "#9ca1ba" }}>
                  {record.dsType}
                </span>
              </div>
            </div>
          );
        },
      },
      {
        title: "连接信息",
        dataIndex: "url",
        width: "30%",
        // lineClampOne: true,
        render(content, record) {
          return (
            <>
              <div>
                <Tooltip title="克隆数据源">
                  <CopyOutlined
                    style={{ cursor: "pointer" }}
                    className="dc-lf-clone-icon"
                    onClick={() => editDrawerRef.current.cloneDs(record)}
                  />
                </Tooltip>
              </div>
              <Tooltip title={content}>
                <div>
                  <span className="dc-lf-clone-label">url: </span>
                  <span style={{ fontWeight: 600 }}>{content}</span>
                </div>
              </Tooltip>
            </>
          );
        },
      },
      // TODO: 两行省略
      {
        title: "描述",
        dataIndex: "description",
        width: "10%",
        // width: 180,
        lineClampOne: true,
      },

      {
        title: "启用状态",
        width: "5%",
        dataIndex: "status",
        render(status: number, record) {
          return (
            <div style={{ width: 60 }}>
              <Switch
                checked={status === 1}
                size="small"
                onChange={() => {
                  request(api.switchStatus, {
                    method: "POST",
                    data: {
                      id: record.id,
                      status: status === 1 ? 2 : 1,
                    },
                  }).then((_) => {
                    getDataSourceList();
                  });
                }}
              />
            </div>
          );
        },
      },
      {
        title: "最后更新时间",
        dataIndex: "createTime",
        width: "10%",
        render: (date) => moment(date).format("YYYY-MM-DD HH:mm:ss"),
      },
      // {
      //   title: "最后更新人",
      //   dataIndex: "createBy",
      //   // width: 100,
      //   width: "10%",
      //   lineClampOne: true,
      // },
    ];

    baseColumns.push({
      title: "操作",
      dataIndex: "",
      width: "10%",
      lineClampOne: false,
      render(record: ConfigProps) {
        return (
          <>
            <Button
              type="link"
              size="small"
              onClick={() =>
                editDrawerRef.current.onOpen(
                  true,
                  ConfigOperate.Edit,
                  getDataSourceList,
                  configGroupList,
                  record
                )
              }
              style={{ paddingLeft: 0 }}
            >
              编辑
            </Button>

            <Divider type="vertical" />

            <Button type="link" size="small" onClick={() => onDelete(record)}>
              删除
            </Button>
          </>
        );
      },
    });

    return baseColumns;
  }, [global, getDataSourceList, configGroupList]);

  const onDelete = (record: ConfigProps) => {
    confirm({
      title: "确定删除数据源吗?",
      content: `数据源 [${record.dsName}] ${
        record.status === 1 ? "为启用状态，无法删除" : ""
      }`,
      centered: true,
      okText: "删除",
      okType: "primary",
      okButtonProps: {
        size: "small",
        disabled: record.status === 1,
        danger: true,
      },
      cancelButtonProps: {
        size: "small",
      },
      maskClosable: true,
      onOk() {
        return HttpUtils.delete(api.delSource + "/" + record.id).then((_) => {
          message.success("删除成功");
          getDataSourceList();
        });
      },
    });
  };

  const onTableChange = (curPagination) => {
    getDataSourceList({
      page: curPagination.current,
      size: curPagination.pageSize,
    });
  };

  useEffect(() => {
    // 获取配置列表
    getDataSourceList();
  }, []);

  useEffect(() => {
    getDsList();
  }, []);

  return (
    <>
      <TypicalListCard title="数据源列表">
        <div className="config-manage-page">
          <div className="operate-bar">
            <div className="left">
              <div className="refresh-icon" onClick={() => getDataSourceList()}>
                <IconFont className="icon" type="icon-shuaxin1" />
              </div>
              <Divider type="vertical" style={{ height: 20, top: 0 }} />
              <Form
                form={form}
                layout="inline"
                onFinish={() => getDataSourceList({ page: 1 })}
              >
                <Form.Item name="dsType">
                  <Select
                    style={{ width: 180 }}
                    placeholder="请选择数据源类型"
                    options={configGroupList}
                  />
                </Form.Item>
                {/* <Form.Item name="valueName">
                  <Input style={{ width: 180 }} placeholder="请输入配置键" />
                </Form.Item> */}
                <Form.Item name="dsName">
                  <Input style={{ width: 180 }} placeholder="请输入名称" />
                </Form.Item>
                <Form.Item>
                  <Button type="primary" ghost htmlType="submit">
                    查询
                  </Button>
                </Form.Item>
              </Form>
            </div>

            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() =>
                editDrawerRef.current.onOpen(
                  true,
                  ConfigOperate.Add,
                  getDataSourceList,
                  configGroupList
                )
              }
            >
              新增数据源
            </Button>
          </div>

          <ProTable
            tableProps={{
              showHeader: false,
              loading,
              rowKey: "id",
              dataSource: data,
              paginationProps: pagination,
              columns: columns as any,
              lineFillColor: true,
              attrs: {
                onChange: onTableChange,
                scroll: {
                  scrollToFirstRowOnChange: true,
                  x: true,
                  y: "calc(100vh - 270px)",
                },
              },
            }}
          />
        </div>
      </TypicalListCard>

      {/* 新增/编辑配置抽屉 */}
      <AddAndEditDataSourceModal ref={editDrawerRef} getDsList={getDsList} />
      <ConfigValueDetail ref={configValueModalRef} />
      {/* <CommonConfig /> */}
    </>
  );
};
